﻿using BAL;
using DAL;
using DAL.DataProvider;
using DAL.DataTransferObject;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Module.QLGiamGia
{
    public partial class frmQLKhuyenMai : Form
    {
        public GiamGiaKH ggkh;
        public GiamGiaHH gghh;
        public HangHoaBAO hhBAO = new HangHoaBAO();

        public GiamGiaHHBAO gghhBAO = new GiamGiaHHBAO();
        public GiamGiaKHBAO ggkhBAO = new GiamGiaKHBAO();
        public frmQLKhuyenMai()
        {
            InitializeComponent();
        }

        Timer timer = new Timer();

        public void getInfo()
        {
            if (tcGiamGia.SelectedIndex == 0)
            {
                ggkh = new GiamGiaKH();
                ggkh.maGiamGia = txtMaGGK.Text;
                ggkh.ngayBatDau = dtNgayBatDau.Value;
                ggkh.ngayKetThuc = dtNgayKetThuc.Value;
                ggkh.maKhachHang = txtMaKH.Text;
                ggkh.ghiChu = txtGhiChu.Text;
                ggkh.chietKhau = Convert.ToInt32(txtChietKhau.Text);
            }
            else
            {
                string[] a = cbMaHang.Text.Split('-');
                gghh = new GiamGiaHH();
                gghh.maGiamGia = txtMaGG1.Text;
                gghh.maHang = a[0].ToString();
                gghh.thoiGianBatDau = dtNgayBatDau1.Value;
                gghh.thoiGianKetThuc = dtNgayKetThuc1.Value;
                gghh.ghiChu = txtGhiChu1.Text;
                gghh.chietKhau = Convert.ToInt32(txtChietKhau1.Text);
            }
        }


        private void btAddNew_Click(object sender, EventArgs e)
        {
            if (tcGiamGia.SelectedIndex == 0)
            {
                try
                {
                    if (dtNgayBatDau.Value > dtNgayKetThuc.Value) throw new Exception("Ngày bắt đầu phải trước ngày hết hạn");
                    if (txtMaKH.Text.Length == 0) throw new Exception("Mã khách hàng không được bỏ trống");
                    if (txtChietKhau.Text.Length < 0) throw new Exception("Chiết khấu phải lớn hơn hoặc bằng 0");
                    getInfo();
                    ggkhBAO.GiamGiaKH_AddNew(ggkh);
                    loadList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "ERROR");
                }
            }
            else
            {
                try
                {
                    if (dtNgayBatDau1.Value > dtNgayKetThuc1.Value) throw new Exception("Ngày bắt đầu phải trước ngày hết hạn");
                    if (cbMaHang.Text.Length == 0) throw new Exception("Mã hàng hóa không được bỏ trống");
                    if (txtChietKhau1.Text.Length <= 0) throw new Exception("Chiết khấu phải lớn hơn 0");
                    getInfo();
                    gghhBAO.GiamGiaHH_AddNew(gghh);
                    loadList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "ERROR");
                }
            }
        }

        public void loadList()
        {
            DGV1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            DGV2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            btDelete.Enabled = false;
            btUpdate.Enabled = false;
            if (tcGiamGia.SelectedTab.Name == "tbKhachHang")
            {
                List<GiamGiaKH> listGGKH = ggkhBAO.GiamGiaKH_GetData();
                DGV1.DataSource = listGGKH;
                int deWidth = 0;
                for (int i = 0; i < DGV1.Columns.Count - 1; i++)
                {
                    deWidth += DGV1.Columns[i].Width;
                }
                for (int i = 0; i < DGV1.Rows.Count; i++)
                {
                    DGV1.Rows[i].Cells[0].Value = (i + 1);
                }
                DGV1.Columns[DGV1.Columns.Count - 1].Width = deWidth;
                txtMaGGK.Text = AutoGenCode.GenNewCode("GiamGiaKhach");

            }
            else
            {
                loadLoaiHang();
                List<GiamGiaHH> listGGHH = gghhBAO.GiamGiaHH_GetData();
                DGV2.DataSource = listGGHH;
                int deWidth = 0;
                for (int i = 0; i < DGV2.Columns.Count - 1; i++)
                {
                    deWidth += DGV2.Columns[i].Width;
                }
                for (int i = 0; i < DGV2.Rows.Count; i++)
                {
                    DGV2.Rows[i].Cells[0].Value = (i + 1);
                }
                DGV2.Columns[DGV2.Columns.Count - 1].Width = deWidth;
                txtMaGG1.Text = (Convert.ToInt32(DGV2.Rows[DGV2.Rows.Count - 1].Cells[1].Value.ToString()) + 1).ToString();
            }
        }

        private void frmQLGiamGia_Load(object sender, EventArgs e)
        {
            loadList();
            btRefresh.PerformClick();
            timer.Interval = 10;
            timer.Start();
            timer.Tick += timer_Tick;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            btRefresh.PerformClick();
            timer.Stop();
        }

        private void tcGiamGia_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SearchClicked)
                btSearchName.PerformClick();
            loadList();
            reset();
        }
        public void loadLoaiHang()
        {
            cboNhomHang.Items.Clear();
            SqlDataReader dr = hhBAO.HangHoa_Get("SELECT DISTINCT LoaiHang FROM HangHoa", "");
            while (dr.Read())
            {
                cboNhomHang.Items.Add(dr["LoaiHang"].ToString());
            }
        }
        public void loadMaHang()
        {
            SqlDataReader dr = hhBAO.HangHoa_Get("SELECT MaHang,TenHang FROM HangHoa", "");
            while (dr.Read())
            {
                cbMaHang.Items.Add(dr["MaHang"].ToString() + "-" + dr["TenHang"].ToString());
            }
        }

        private void cboNhomHang_SelectedIndexChanged(object sender, EventArgs e)
        {

            //string a = "";
            //if (cboNhomHang.SelectedItem.ToString()=="All")
            //    a = "SELECT MaHang,TenHang FROM HangHoa";
            //else
            //    a = "SELECT MaHang,TenHang FROM HangHoa WHERE LoaiHang=@LoaiHang";
            cbMaHang.Items.Clear();

            SqlDataReader dr = hhBAO.HangHoa_Get("SELECT MaHang,TenHang FROM HangHoa WHERE LoaiHang=@LoaiHang", cboNhomHang.Text);
            while (dr.Read())
            {
                cbMaHang.Items.Add(dr["MaHang"].ToString() + "-" + dr["TenHang"].ToString());
            }



        }

        public void reset()
        {
            if (tcGiamGia.SelectedIndex == 0)
            {
                txtMaGGK.Text = AutoGenCode.GenNewCode("GiamGiaKhach");
                dtNgayBatDau.Value = DateTime.Now;
                dtNgayKetThuc.Value = DateTime.Now;
                txtMaKH.Clear();
                txtChietKhau.Clear();
                txtGhiChu.Clear();
                btUpdate.Enabled = false;
                btDelete.Enabled = false;
                btAddNew.Enabled = true;
            }
            else
            {
                txtMaGG1.Text = AutoGenCode.GenNewCode("GiamGiaHang");
                dtNgayBatDau1.Value = DateTime.Now;
                dtNgayKetThuc1.Value = DateTime.Now;
                txtMaKH.Clear();
                txtChietKhau1.Clear();
                txtGhiChu1.Clear();
                btUpdate.Enabled = false;
                btDelete.Enabled = false;
                btAddNew.Enabled = true;
                cbMaHang.Text = "";
                cboNhomHang.Text = "";
            }
            btSearchName.Enabled = true;
        }

        private void DGV1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DGV1.SelectedRows.Count>0)
            {
                if (SearchClicked)
                {
                    DataView dvTemp = new DataView();
                    dvTemp = ggkhBAO.SelectAllViewGGK();
                    int rowIndex = AutoGenCode.GetRealIndexOfRow(DGV1.SelectedRows[0].Cells[1].Value.ToString(), dvTemp, 0);
                    btSearchName.PerformClick();
                    //DGV1.ClearSelection();
                    //DGV1.CurrentRow.Selected = false;
                    DGV1.CurrentCell = DGV1[0, rowIndex];
                    //MessageBox.Show(rowIndex.ToString());
                }
                btAddNew.Enabled = false;
                btUpdate.Enabled = true;
                btDelete.Enabled = true;
                txtMaGGK.Text = DGV1.SelectedRows[0].Cells[1].Value.ToString();
                dtNgayBatDau.Value = Convert.ToDateTime(DGV1.SelectedRows[0].Cells[2].Value.ToString());
                dtNgayKetThuc.Value = Convert.ToDateTime(DGV1.SelectedRows[0].Cells[3].Value.ToString());
                txtGhiChu.Text = DGV1.SelectedRows[0].Cells[4].Value.ToString();
                txtMaKH.Text = DGV1.SelectedRows[0].Cells[5].Value.ToString();
                txtChietKhau.Text = DGV1.SelectedRows[0].Cells[6].Value.ToString();
            }
        }

        private void DGV2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            loadMaHang();
            btAddNew.Enabled = false;
            btUpdate.Enabled = true;
            btDelete.Enabled = true;
            btSearchName.Enabled = false;
            txtMaGG1.Text = DGV2.SelectedRows[0].Cells[1].Value.ToString();
            dtNgayBatDau1.Value = Convert.ToDateTime(DGV2.SelectedRows[0].Cells[3].Value);
            dtNgayKetThuc1.Value = Convert.ToDateTime(DGV2.SelectedRows[0].Cells[4].Value);
            txtGhiChu1.Text = DGV2.SelectedRows[0].Cells[5].Value.ToString();
            txtChietKhau1.Text = DGV2.SelectedRows[0].Cells[6].Value.ToString();
            for (int i = 0; i < cbMaHang.Items.Count; i++)
            {
                if (cbMaHang.Items[i].ToString().Contains(DGV2.SelectedRows[0].Cells[2].Value.ToString()))
                {

                    cbMaHang.Text = cbMaHang.Items[i].ToString();
                    SqlDataReader dr = hhBAO.HangHoa_Get("SELECT LoaiHang FROM HangHoa WHERE MaHang=@MaHang", DGV2.SelectedRows[0].Cells[2].Value.ToString());
                    while (dr.Read())
                    {
                        cboNhomHang.Text = dr["LoaiHang"].ToString();
                    }

                }
            }
            //SqlDataReader dr = hhBAO.HangHoa_Get("SELECT LoaiHang FROM HangHoa WHERE MaHang=@MaHang", DGV2.SelectedRows[0].Cells[2].Value.ToString());
            //while (dr.Read())
            //{
            //    cboNhomHang.Text = dr["LoaiHang"].ToString();
            //}
            //SqlCommand dr1 = new SqlCommand("select Tenhang from hangHoa where mahang=@mahang",DataAccess.GetConnection());
            //dr1.Parameters.AddWithValue("@mahang", DGV2.SelectedRows[0].Cells[2].Value.ToString());
            //SqlDataAdapter da = new SqlDataAdapter(dr1);
            //DataTable dv = new DataTable();
            //da.Fill(dv);
            //cbMaHang.Text =DGV2.SelectedRows[0].Cells[2].Value.ToString()+"-"+dv.Rows[0]["tenhang"].ToString();

        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            reset();
            loadList();
        }

        private void btUpdate_Click(object sender, EventArgs e)
        {
            if (tcGiamGia.SelectedIndex == 0)
            {
                getInfo();
                ggkhBAO.GiamGiaKH_Update(ggkh);
                loadList();
                reset();
            }
            else
            {
                getInfo();
                gghhBAO.GiamGiaHH_Update(gghh);
                loadList();
                reset();
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            if (tcGiamGia.SelectedIndex == 0)
            {
                getInfo();
                ggkh.ghiChu = "NO";
                ggkhBAO.GiamGiaKH_Update(ggkh);
                loadList();
                reset();
            }
            else
            {
                getInfo();
                gghh.ghiChu = "NO";
                gghhBAO.GiamGiaHH_Update(gghh);
                loadList();
                reset();
            }
        }

        //bool SearchClicked = false;
        private string ToStringFilter(List<string> list)
        {
            Console.WriteLine(list.Count.ToString());
            string s = "";
            if (list.Count >= 2)
                for (int i = 0; i < list.Count - 1; i++)
                    s += list.ToArray()[i] + " AND ";
            s += list.ToArray()[list.Count - 1];
            return s;
        }


        DataView dv = new DataView();
        bool SearchClicked = false;
        List<string> listStringFilter = new List<string>();

        private void btSearchName_Click(object sender, EventArgs e)
        {
            if (!SearchClicked)
            {
                SearchClicked = true;
                btRefresh.PerformClick();
                btSearchName.BackgroundImage = (Image)(Module.QLKhuyenMai.Properties.Resources.ResourceManager.GetObject("TatTK"));
                if (tcGiamGia.SelectedIndex == 0)
                {
                    txtMaGGK.Text = txtMaKH.Text = txtChietKhau.Text = txtGhiChu.Text = "";
                    dtNgayBatDau.Value = dtNgayBatDau.MinDate;
                    dtNgayKetThuc.Value = dtNgayKetThuc.MaxDate;
                    btUpdate.Enabled = btDelete.Enabled = false;
                    DGV1.DataSource = ggkhBAO.GiamGiaKH_GetData();
                }
                else
                {
                    txtMaGG1.Text = txtChietKhau1.Text = txtGhiChu1.Text = "";
                    dtNgayBatDau1.Value = dtNgayBatDau.MinDate;
                    dtNgayKetThuc1.Value = dtNgayKetThuc.MaxDate;
                    btUpdate.Enabled = btDelete.Enabled = false;
                    DGV2.DataSource = gghhBAO.GiamGiaHH_GetData();
                }
            }
            else
            {
                SearchClicked = false;
                btRefresh.PerformClick();
                btSearchName.BackgroundImage = (Image)(Module.QLKhuyenMai.Properties.Resources.ResourceManager.GetObject("BatTK"));
                if (tcGiamGia.SelectedIndex == 0)
                {
                    txtMaGGK.Text = txtMaKH.Text = txtChietKhau.Text = txtGhiChu.Text = "";
                    txtMaGGK.ReadOnly = true;
                    dtNgayBatDau.Value = dtNgayKetThuc.Value = DateTime.Today;
                    btUpdate.Enabled = btDelete.Enabled = true;
                    DGV1.DataSource = ggkhBAO.GiamGiaKH_GetData();
                }
                else
                {
                    txtMaGG1.Text = txtChietKhau1.Text = txtGhiChu1.Text = "";
                    txtMaGG1.ReadOnly = true;
                    dtNgayBatDau1.Value = dtNgayKetThuc1.Value = DateTime.Today;
                    btUpdate.Enabled = btDelete.Enabled = true;
                    DGV2.DataSource = gghhBAO.GiamGiaHH_GetData();
                }
            }
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void FilterChanged(object sender, EventArgs e)
        {
            if (SearchClicked)
            {
                if (tcGiamGia.SelectedIndex==0)
                {
                    dv = ggkhBAO.SelectAllViewGGK();
                    listStringFilter = new List<string>();
                    listStringFilter.Add(String.Format("Convert(ChietKhau,System.String) like '{0}%'", txtChietKhau.Text));
                    listStringFilter.Add(String.Format("GhiChu like '{0}%'", txtGhiChu.Text));
                    listStringFilter.Add(String.Format("Convert(MaGiamGiaKhach,System.String) like '{0}%'", txtMaGGK.Text));
                    listStringFilter.Add(String.Format("MaKhachHang like '{0}%'", txtMaKH.Text));
                    listStringFilter.Add(String.Format("NgayBatDau >= '{0}'", dtNgayBatDau.Value));
                    listStringFilter.Add(String.Format("NgayKetThuc <='{0}'", dtNgayKetThuc.Value));
                    dv.RowFilter = ToStringFilter(listStringFilter);
                    DGV1.DataSource = dv;
                }
                else
                {
                    string[] a = cbMaHang.Text.Split('-');
                    dv = gghhBAO.SelectAllViewGGH();
                    listStringFilter = new List<string>();
                    listStringFilter.Add(String.Format("Convert(ChietKhau,System.String) like '{0}%'", txtChietKhau1.Text));
                    listStringFilter.Add(String.Format("NgayBatDau >= '{0}'", dtNgayBatDau1.Value));
                    listStringFilter.Add(String.Format("NgayKetThuc <='{0}'", dtNgayKetThuc1.Value));
                    listStringFilter.Add(String.Format("MaHang like '%{0}%'", a[0].ToString()));
                    dv.RowFilter = ToStringFilter(listStringFilter);
                    DGV2.DataSource = dv;
                    Console.Write(a[0].ToString());
                }
            }
        }








    }
}
